<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>旅行社系统 - 酒店订单</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css">
    <link rel="stylesheet" href="css/main.css">
    <!-- Vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
    <div id="app">
        <div class="container-fluid">
            <div class="row">
                <sidebar-nav 
                    current-page="hotel-orders"
                    @logout="handleLogout">
                </sidebar-nav>

                <!-- 主内容区 -->
                <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                        <h1 class="h2">酒店订单管理</h1>
                        <div class="btn-toolbar mb-2 mb-md-0">
                            <button type="button" class="btn btn-primary" @click="showCreateModal">
                                <i class="bi bi-plus-circle"></i> 新增酒店订单
                            </button>
                        </div>
                    </div>

                    <!-- 搜索栏 -->
                    <div class="row mb-3">
                        <div class="col-md-3">
                            <input type="text" class="form-control" v-model="searchQuery.CityName" placeholder="城市名称">
                        </div>
                        <div class="col-md-3">
                            <input type="text" class="form-control" v-model="searchQuery.HotelName" placeholder="酒店名称">
                        </div>
                        <div class="col-md-3">
                            <button class="btn btn-primary" @click="searchOrders">
                                <i class="bi bi-search"></i> 搜索
                            </button>
                            <button class="btn btn-secondary ms-2" @click="resetSearch">
                                <i class="bi bi-x-circle"></i> 重置
                            </button>
                        </div>
                    </div>

                    <!-- 订单列表 -->
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>城市</th>
                                    <th>酒店名称</th>
                                    <th>关联订单</th>
                                    <th>房型</th>
                                    <th>房间数</th>
                                    <th>入住日期</th>
                                    <th>天数</th>
                                    <th>单价</th>
                                    <th>总价</th>
                                    <th>联系人</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr v-if="orders.length === 0">
                                    <td colspan="11" class="text-center">暂无数据</td>
                                </tr>
                                <tr v-else v-for="order in orders" :key="order.ID">
                                    <td>{{ order.CityName }}</td>
                                    <td>{{ order.HotelName }}</td>
                                    <td>{{ order.package_order_title || '-' }}</td>
                                    <td>{{ order.RoomType }}</td>
                                    <td>{{ order.BookRoomCount }}</td>
                                    <td>{{ formatDate(order.CheckInTime) }}</td>
                                    <td>{{ order.StayDayCount }}</td>
                                    <td>{{ formatPrice(order.RoomUnitPrice) }}</td>
                                    <td>{{ formatPrice(order.TotalPrice) }}</td>
                                    <td>{{ order.ContactName }}</td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-primary me-1" @click="showEditModal(order)">
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-success me-1" @click="showPassengersModal(order)">
                                            <i class="bi bi-people"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-warning me-1" @click="showPackageOrdersModal(order)">
                                            <i class="bi bi-link-45deg"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-secondary me-1" @click="showOrderDetail(order)">
                                            <i class="bi bi-info-circle"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-danger" @click="handleDelete(order)">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </main>
            </div>
        </div>

        <!-- 新增/编辑订单模态框 -->
        <div class="modal fade" id="orderModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">{{ isEditing ? '编辑酒店订单' : '新增酒店订单' }}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form @submit.prevent="handleSubmit">
                            <!-- 基本信息 -->
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label class="form-label">城市名称</label>
                                    <input type="text" class="form-control" v-model="form.CityName" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">酒店名称</label>
                                    <input type="text" class="form-control" v-model="form.HotelName" required>
                                </div>
                            </div>

                            <!-- 房间信息 -->
                            <div class="row mb-3">
                                <div class="col-md-4">
                                    <label class="form-label">房间类型</label>
                                    <input type="text" class="form-control" v-model="form.RoomType" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">房间单价</label>
                                    <input type="number" class="form-control" v-model="form.RoomUnitPrice" step="0.01" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">预订房间数</label>
                                    <input type="number" class="form-control" v-model.number="form.BookRoomCount" min="1" required>
                                </div>
                            </div>

                            <!-- 入住信息 -->
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label class="form-label">入住日期</label>
                                    <input type="date" class="form-control" v-model="form.CheckInTime" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">入住天数</label>
                                    <input type="number" class="form-control" v-model.number="form.StayDayCount" min="1" required>
                                </div>
                            </div>

                            <!-- 联系人信息 -->
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label class="form-label">联系人姓名</label>
                                    <input type="text" class="form-control" v-model="form.ContactName" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">联系人电话</label>
                                    <input type="text" class="form-control" v-model="form.ContactTelNo" required>
                                </div>
                            </div>

                            <!-- 关联信息 -->
                            <div class="row mb-3">
                                <div class="col-md-4">
                                    <label class="form-label">打包订单ID</label>
                                    <input type="number" class="form-control" v-model.number="form.package_order_id">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">关联订单标题</label>
                                    <input type="text" class="form-control" v-model="form.package_order_title">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">客户档案ID</label>
                                    <input type="number" class="form-control" v-model.number="form.customer_profile_id">
                                </div>
                            </div>

                            <!-- 总价信息（只读） -->
                            <div class="row mb-3">
                                <div class="col-md-12">
                                    <label class="form-label">总价</label>
                                    <input type="text" class="form-control" :value="formatPrice(form.TotalPrice)" readonly>
                                    <small class="form-text text-muted">总价由系统自动计算（单价 × 房间数 × 天数）</small>
                                </div>
                            </div>

                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                                <button type="submit" class="btn btn-primary">保存</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- 添加乘客管理模态框 -->
        <div class="modal fade" id="passengersModal" tabindex="-1">
            <div class="modal-dialog modal-xl">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">管理入住人信息</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <button class="btn btn-primary" @click="showAddPassengerModal">
                                <i class="bi bi-plus-circle"></i> 添加入住人
                            </button>
                        </div>
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>姓名</th>
                                        <th>证件类型</th>
                                        <th>证件号码</th>
                                        <th>生日</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-if="passengers.length === 0">
                                        <td colspan="5" class="text-center">暂无入住人信息</td>
                                    </tr>
                                    <tr v-else v-for="passenger in passengers" :key="passenger.ID">
                                        <td>{{ passenger.Name }}</td>
                                        <td>{{ getCertificateTypeText(passenger.CertificateType) }}</td>
                                        <td>{{ passenger.CertificateNo }}</td>
                                        <td>{{ formatDate(passenger.BirthdayDTS) }}</td>
                                        <td>
                                            <button class="btn btn-sm btn-outline-primary me-1" @click="showEditPassengerModal(passenger)">
                                                <i class="bi bi-pencil"></i>
                                            </button>
                                            <button class="btn btn-sm btn-outline-danger" @click="handleDeletePassenger(passenger)">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 添加乘客表单模态框 -->
        <div class="modal fade" id="passengerFormModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">{{ isEditingPassenger ? '编辑入住人' : '添加入住人' }}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form @submit.prevent="handlePassengerSubmit">
                            <div class="mb-3">
                                <label class="form-label">姓名</label>
                                <input type="text" class="form-control" v-model="passengerForm.Name" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">证件类型</label>
                                <select class="form-select" v-model="passengerForm.CertificateType" required>
                                    <option value="passport">护照</option>
                                    <option value="id_card">身份证</option>
                                    <option value="other">其他</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">证件号码</label>
                                <input type="text" class="form-control" v-model="passengerForm.CertificateNo" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">生日</label>
                                <input type="date" class="form-control" v-model="passengerForm.BirthdayDTS" required>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                                <button type="submit" class="btn btn-primary">保存</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- 添加跟团游订单搜索列表模态框 -->
        <div class="modal fade" id="packageOrdersModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">关联跟团游订单</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <!-- 搜索栏 -->
                        <div class="row mb-3">
                            <div class="col-md-8">
                                <input type="text" class="form-control" v-model="packageOrderSearchQuery" placeholder="搜索订单标题...">
                            </div>
                            <div class="col-md-4">
                                <button class="btn btn-primary" @click="searchPackageOrders">
                                    <i class="bi bi-search"></i> 搜索
                                </button>
                                <button class="btn btn-secondary ms-2" @click="resetPackageOrderSearch">
                                    <i class="bi bi-x-circle"></i> 重置
                                </button>
                            </div>
                        </div>
                        
                        <!-- 订单列表 -->
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>订单ID</th>
                                        <th>订单标题</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-if="packageOrders.length === 0">
                                        <td colspan="3" class="text-center">暂无数据</td>
                                    </tr>
                                    <tr v-else v-for="order in packageOrders" :key="order.ID">
                                        <td>{{ order.ID }}</td>
                                        <td>{{ order.title }}</td>
                                        <td>
                                            <button class="btn btn-sm btn-primary" @click="selectPackageOrder(order)">
                                                选择
                                            </button>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="js/api/config.js"></script>
    <script src="js/api/auth.js"></script>
    <script src="js/components/Sidebar.js"></script>
    <script>
        new Vue({
            el: '#app',
            data: {
                orders: [],
                searchQuery: {
                    CityName: '',
                    HotelName: ''
                },
                form: {
                    package_order_id: -1,
                    package_order_title: '',
                    customer_profile_id: 0,
                    CityName: '',
                    HotelName: '',
                    RoomType: '',
                    RoomUnitPrice: '0',
                    BookRoomCount: 0,
                    TotalPrice: '0',
                    CheckInTime: '',
                    StayDayCount: 0,
                    ContactName: '',
                    ContactTelNo: ''
                },
                isEditing: false,
                currentEditingOrder: null,
                orderModal: null,
                passengers: [],
                isEditingPassenger: false,
                currentEditingPassenger: null,
                currentHotelOrder: null,
                passengerForm: {
                    Name: '',
                    CertificateType: 'passport',
                    CertificateNo: '',
                    BirthdayDTS: ''
                },
                packageOrderSearchQuery: '',
                packageOrders: [],
                packageOrdersModal: null,
                currentLinkingOrder: null
            },
            mounted() {
                this.$nextTick(() => {
                    const modalEl = document.getElementById('orderModal');
                    if (modalEl) {
                        this.orderModal = new bootstrap.Modal(modalEl);
                    }
                });
                this.$nextTick(() => {
                    const passengersModalEl = document.getElementById('passengersModal');
                    const passengerFormModalEl = document.getElementById('passengerFormModal');
                    if (passengersModalEl) {
                        this.passengersModal = new bootstrap.Modal(passengersModalEl);
                    }
                    if (passengerFormModalEl) {
                        this.passengerFormModal = new bootstrap.Modal(passengerFormModalEl);
                    }
                });
                this.$nextTick(() => {
                    const packageOrdersModalEl = document.getElementById('packageOrdersModal');
                    if (packageOrdersModalEl) {
                        this.packageOrdersModal = new bootstrap.Modal(packageOrdersModalEl);
                    }
                });
                this.loadOrders();
            },
            methods: {
                async loadOrders() {
                    try {
                        const response = await window.apiClient.get('/api/hotel-orders', {
                            params: this.searchQuery
                        });
                        this.orders = Array.isArray(response.data) ? response.data : [];
                    } catch (error) {
                        console.error('加载酒店订单失败:', error);
                        alert('加载酒店订单失败');
                    }
                },
                formatDate(date) {
                    return new Date(date).toLocaleDateString('zh-CN');
                },
                formatPrice(price) {
                    const numPrice = typeof price === 'string' ? parseFloat(price) : price;
                    return numPrice.toFixed(2);
                },
                showCreateModal() {
                    this.isEditing = false;
                    this.currentEditingOrder = null;
                    this.resetForm();
                    this.orderModal.show();
                },
                showEditModal(order) {
                    this.isEditing = true;
                    this.currentEditingOrder = order;
                    this.form = {
                        ...order,
                        CheckInTime: order.CheckInTime.split('T')[0]
                    };
                    this.orderModal.show();
                },
                async handleSubmit() {
                    try {
                        const totalPrice = (parseFloat(this.form.RoomUnitPrice) * this.form.BookRoomCount * this.form.StayDayCount).toString();
                        
                        const submitData = {
                            package_order_id: this.form.package_order_id,
                            package_order_title: this.form.package_order_title,
                            customer_profile_id: this.form.customer_profile_id,
                            CityName: this.form.CityName,
                            HotelName: this.form.HotelName,
                            RoomType: this.form.RoomType,
                            RoomUnitPrice: this.form.RoomUnitPrice.toString(),
                            BookRoomCount: this.form.BookRoomCount,
                            TotalPrice: totalPrice,
                            CheckInTime: this.form.CheckInTime + 'T00:00:00',
                            StayDayCount: this.form.StayDayCount,
                            ContactName: this.form.ContactName,
                            ContactTelNo: this.form.ContactTelNo
                        };

                        if (this.isEditing) {
                            await window.apiClient.put(`/api/hotel-orders/${this.currentEditingOrder.ID}`, submitData);
                        } else {
                            await window.apiClient.post('/api/hotel-orders/', submitData);
                        }

                        this.orderModal.hide();
                        await this.loadOrders();
                        this.resetForm();
                        alert(this.isEditing ? '酒店订单更新成功！' : '酒店订单创建成功！');
                    } catch (error) {
                        console.error(this.isEditing ? '更新酒店订单失败:' : '创建酒店订单失败:', error);
                        alert(error.response?.data?.detail || (this.isEditing ? '更新酒店订单失败' : '创建酒店订单失败'));
                    }
                },
                async handleDelete(order) {
                    if (!confirm('确定要删除这个酒店订单吗？')) return;
                    try {
                        await window.apiClient.delete(`/api/hotel-orders/${order.ID}`);
                        await this.loadOrders();
                        alert('酒店订单删除成功！');
                    } catch (error) {
                        console.error('删除酒店订单失败:', error);
                        alert('删除酒店订单失败');
                    }
                },
                resetForm() {
                    this.form = {
                        package_order_id: -1,
                        package_order_title: '',
                        customer_profile_id: 0,
                        CityName: '',
                        HotelName: '',
                        RoomType: '',
                        RoomUnitPrice: '0',
                        BookRoomCount: 0,
                        TotalPrice: '0',
                        CheckInTime: '',
                        StayDayCount: 0,
                        ContactName: '',
                        ContactTelNo: ''
                    };
                },
                searchOrders() {
                    this.loadOrders();
                },
                resetSearch() {
                    this.searchQuery = {
                        CityName: '',
                        HotelName: ''
                    };
                    this.loadOrders();
                },
                handleLogout() {
                    auth.logout();
                },
                async showPassengersModal(order) {
                    this.currentHotelOrder = order;
                    await this.loadPassengers(order.ID);
                    this.passengersModal.show();
                },
                async loadPassengers(orderId) {
                    try {
                        const response = await window.apiClient.get(`/api/hotel/orders/${orderId}/passengers`);
                        this.passengers = Array.isArray(response.data) ? response.data : [];
                    } catch (error) {
                        console.error('加载入住人信息失败:', error);
                        alert('加载入住人信息失败');
                    }
                },
                getCertificateTypeText(type) {
                    const types = {
                        'passport': '护照',
                        'id_card': '身份证',
                        'other': '其他'
                    };
                    return types[type] || type;
                },
                showAddPassengerModal() {
                    this.isEditingPassenger = false;
                    this.currentEditingPassenger = null;
                    this.resetPassengerForm();
                    this.passengerFormModal.show();
                },
                showEditPassengerModal(passenger) {
                    this.isEditingPassenger = true;
                    this.currentEditingPassenger = passenger;
                    this.passengerForm = {
                        ...passenger,
                        BirthdayDTS: passenger.BirthdayDTS.split('T')[0]
                    };
                    this.passengerFormModal.show();
                },
                async handlePassengerSubmit() {
                    try {
                        const submitData = {
                            ...this.passengerForm,
                            hotel_order_id: this.currentHotelOrder.ID
                        };

                        if (this.isEditingPassenger) {
                            await window.apiClient.put(`/api/hotel/orders/${this.currentHotelOrder.ID}/passengers/${this.currentEditingPassenger.ID}`, submitData);
                        } else {
                            await window.apiClient.post(`/api/hotel/orders/${this.currentHotelOrder.ID}/passengers`, submitData);
                        }

                        this.passengerFormModal.hide();
                        await this.loadPassengers(this.currentHotelOrder.ID);
                        alert(this.isEditingPassenger ? '入住人信息更新成功！' : '入住人信息添加成功！');
                    } catch (error) {
                        console.error(this.isEditingPassenger ? '更新入住人信息失败:' : '添加入住人信息失败:', error);
                        alert(error.response?.data?.detail || (this.isEditingPassenger ? '更新入住人信息失败' : '添加入住人信息失败'));
                    }
                },
                async handleDeletePassenger(passenger) {
                    if (!confirm('确定要删除这个入住人信息吗？')) return;
                    try {
                        await window.apiClient.delete(`/api/hotel/orders/${this.currentHotelOrder.ID}/passengers/${passenger.ID}`);
                        await this.loadPassengers(this.currentHotelOrder.ID);
                        alert('入住人信息删除成功！');
                    } catch (error) {
                        console.error('删除入住人信息失败:', error);
                        alert('删除入住人信息失败');
                    }
                },
                resetPassengerForm() {
                    this.passengerForm = {
                        Name: '',
                        CertificateType: 'passport',
                        CertificateNo: '',
                        BirthdayDTS: ''
                    };
                },
                async showPackageOrdersModal(order) {
                    this.currentLinkingOrder = order;
                    this.loadPackageOrders();
                    this.packageOrdersModal.show();
                },
                async loadPackageOrders() {
                    try {
                        const response = await window.apiClient.get('/api/package-orders', {
                            params: {
                                title: this.packageOrderSearchQuery
                            }
                        });
                        this.packageOrders = Array.isArray(response.data) ? response.data : [];
                    } catch (error) {
                        console.error('加载跟团游订单失败:', error);
                        alert('加载跟团游订单失败');
                    }
                },
                searchPackageOrders() {
                    this.loadPackageOrders();
                },
                resetPackageOrderSearch() {
                    this.packageOrderSearchQuery = '';
                    this.loadPackageOrders();
                },
                async selectPackageOrder(packageOrder) {
                    try {
                        await window.apiClient.put(`/api/hotel-orders/${this.currentLinkingOrder.ID}`, {
                            package_order_id: packageOrder.ID,
                            package_order_title: packageOrder.title
                        });
                        
                        this.packageOrdersModal.hide();
                        await this.loadOrders();
                        alert('关联跟团游订单成功！');
                    } catch (error) {
                        console.error('关联跟团游订单失败:', error);
                        alert('关联跟团游订单失败');
                    }
                },
                showOrderDetail(order) {
                    window.location.href = `hotel-order-detail.html?id=${order.ID}`;
                }
            }
        });
    </script>
</body>
</html> 